<?php
declare (strict_types = 1);

namespace app\console\middleware;

use think\facade\Log;
use think\facade\Cache;
use think\facade\Route;

class RepeatRequest
{
    /**
     * 处理请求参数
     * 重复请求中间件 根据IP处理频繁请求
     */
    public function handle($request, \Closure $next)
    {

        if((in_array($request->action(),['create','update']) && $request->isPost())){
            $key = $request->ip() . '_' . $request->controller() . '/' . $request->action();
            $cache = Cache::get($key);
            Cache::set($key, 'repeat_request', 1);
            if ($cache) {
                if($request->isAjax()){
                    abort(json(['code'=>400,'msg'=>'请求过于频繁']));
                }else{
                    win('操作成功', Route::buildUrl('index'));
                    fail('请求过于频繁');
                }

            }
        }
        return $next($request);
    }

}
